package com.zfei.gfb.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author fgh
 */
public class Nets {

    /**
     * Pre-loaded local address
     */
    private static InetAddress localAddress;

    static {
        try {
            localAddress = getLocalInetAddress();
        } catch (SocketException e) {
            throw new RuntimeException("fail to get local address");
        }
    }

    /**
     * Retrieve the first validated local ip address(the Public and LAN ip addresses are validated).
     *
     * @return the local address
     * @throws SocketException the socket exception
     */
    private static InetAddress getLocalInetAddress() throws SocketException {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            if (ni.isLoopback()) {
                continue;
            }

            Enumeration<InetAddress> ias = ni.getInetAddresses();
            while (ias.hasMoreElements()) {
                InetAddress address = ias.nextElement();
                if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) {
                    continue;
                }
                return address;
            }
        }

        throw new RuntimeException("no validated local address");
    }

    /**
     * Retrieve local address
     *
     * @return local address
     */
    public static InetAddress getLocalAddress() {
        return localAddress;
    }

    /**
     * Retrieve local host address
     *
     * @return local host address
     */
    public static String getLocalHostAddress() {
        return localAddress.getHostAddress();
    }

    /**
     * Retrieve local host address
     *
     * @return local host address
     */
    public static String getLocalHostName() {
        return localAddress.getHostName();
    }
}
